import React, { useEffect, useState } from "react";
import {
  Space,
  Table,
  Tag,
  TableColumnsType,
  TableProps,
  Button,
  Modal,
  Form,
  Input,
  Radio
} from "antd";

import { useSearchRoleQuery, role, roleType, useAddRoleMutation, useDeleteRoleMutation, useEditRoleMutation } from "@/store/apiSlice";

const { Column } = Table;

// interface Values {
//   title?: string;
//   description?: string;
//   modifier?: string;
// }
const Role: React.FC = () => {
  const { data, isFetching, isError,refetch } = useSearchRoleQuery({ name: "" });
 
  const [form] = Form.useForm();
  const [formValues, setFormValues] = useState<role>();
  const [open, setOpen] = useState(false);

  const [addRole, { isLoading:addLoading }] = useAddRoleMutation();
  const [deleteRole, { isLoading:deleteLoading }] = useDeleteRoleMutation();
  const [modifyRole, { isLoading:modifyLoading}] = useEditRoleMutation();

  const onCreate = async (values: role) => {
    console.log('Received values of form: ', values);
    if(values.id){
      await modifyRole(values);
    }else{
      await addRole(values);
    }
    // form.resetFields();
    setFormValues({name:'',id:0});

    setOpen(false);
  };
  const editRole = (record:role)=>{
    setOpen(true);
    setFormValues(record);
  };
  const columns: TableColumnsType<role> = [
    { title: "更新时间", dataIndex: "updatedAt" },
    { title: "角色名称", dataIndex: "name" },
    {
      title: "操作",
      dataIndex: "action",
      render: (_, record) => (
        <Space size="middle">
          <a>授权</a>
          <a onClick={() => editRole(record)}>编辑</a>
          <a onClick={() => deleteRole(record.id)}>删除</a>
        </Space>
      ),
    },
  ];
  // const dataSource = Array.from<role>({ length: 46 }).map<role>((_, i) => ({
  //   key: i,
  //   name: `Edward King ${i}`,
  //   age: 32,
  //   address: `London, Park Lane no. ${i}`,
  // }));
  // useEffect(() => {
  //     if (isFetching) {
  //         // const containerClassname = classnames('posts-container', {
  //         //   disabled: isFetching
  //         // })
  //         // content = <div className={containerClassname}>{renderedPosts}</div>
  //       } else if (isError) {
  //         // console.error('Failed to fetch post details: ', error);
  //       }
  // },[isFetching]);
  // if (isFetching) {
  //   return <>加载中....</>;
  // }
  if (!data) {
    return "";
  }
  return (
    <>
      <Button onClick={() => refetch()}>查询</Button>
      <Button onClick={() => {setFormValues(()=>{name:""});setOpen(true)}}>新增</Button>
      <Table<role> loading={isFetching} dataSource={data.data.rows} columns={columns} rowKey="id">
        {/* <Column title="" dataIndex="firstName" key="firstName" />
        <Column title="Last Name" dataIndex="lastName" key="lastName" />
        <Column title="Age" dataIndex="age" key="age" />
        <Column title="Address" dataIndex="address" key="address" /> */}

        <Column
          title="action"
          key="action"
          render={(_: any, record: role) => (
            <Space size="middle">
              <a>Invite {record.name}</a>
              <a onClick={() => deleteRole(record.id)}>Delete</a>
            </Space>
          )}
        />
      </Table>

      <Modal
        title="创建角色"
        okText="确定"
        cancelText="取消"
        open={open}
        okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
        // onOk={handleOk}
        destroyOnClose
        onCancel={() => setOpen(false)}
        modalRender={(dom) => (
          <Form
            form={form}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            name="form_in_modal"
            initialValues={formValues}
            clearOnDestroy
            onFinish={(values) => onCreate(values)}
          >
            {dom}
          </Form>
        )}
      >
        <Form.Item
          name="id"
          label="角色名称"
          hidden
          rules={[{ required: false, message: '请输入!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="name"
          label="角色名称"
          rules={[{ required: true, message: '请输入!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item name="description" label="描述">
          <Input type="textarea" />
        </Form.Item>
      </Modal>
    </>
  );
};

export default Role;
